package com.example.demo.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.util.HtmlUtils;

import com.example.demo.entify.Menu;
import com.example.demo.entify.Role;
import com.example.demo.entify.User;
import com.example.demo.entify.UserRole;
import com.example.demo.result.Result;
import com.example.demo.result.ResultFactory;
import com.example.demo.service.UserRoleService;
import com.example.demo.service.UserService;
import com.example.demo.util.TokenUtil;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;

	@Autowired
	private UserRoleService uRoleService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public Result login(@RequestBody User requestUser) {
		String username = requestUser.getUsername();
		String password = requestUser.getPassword();
		Subject subject = SecurityUtils.getSubject();
		User user = uRoleService.findRoleByname(username);
		Integer roleId = user.getRoles().getId();
		;
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
		try {
			subject.login(usernamePasswordToken);
			String token = TokenUtil.sign(requestUser);
			HashMap<String, Object> hs = new HashMap<>();
			hs.put("token", token);
			hs.put("username", username);
			hs.put("password", password);
			hs.put("roleId", roleId);
			return ResultFactory.buildSuccessFactory(hs);
		} catch (AuthenticationException e) {

			String message = "账号密码错误";
			return ResultFactory.buildFailFactory(message);

		}
	}

	@GetMapping("/logout")
	public Result logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		String message = "成功登出";
		return ResultFactory.buildSuccessFactory(message);
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public Result register(@RequestBody User user) {
		String username = user.getUsername();

		String password = user.getPassword();
		username = HtmlUtils.htmlEscape(username);
		System.out.println(user);

		user.setUsername(username);
		User exist = userService.isExist(username);

		if (exist != null) {
			String message = "用户名已被使用";

			return ResultFactory.buildFailFactory(message);
		}
		// 生成盐,默认长度 16 位

		String salt = new SecureRandomNumberGenerator().nextBytes().toString();

		int times = 2;
		// 得到 hash 后的密码
		String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
		// 存储用户信息，包括 salt 与 hash 后的密码
		user.setSalt(salt);
		user.setPassword(encodedPassword);
		userService.register(user);
		UserRole userRole = new UserRole();

		userRole.setUid(user.getId());
		userRole.setRid(user.getRoles().getId());

		uRoleService.saveUserRole(userRole);

		return ResultFactory.buildSuccessFactory(true);

	}

	@RequestMapping(value = "/findWorkers", method = RequestMethod.POST)

	public Result findWokers(Integer id) {

		List<Role> workersList = userService.Workers(id);

	 	

		return ResultFactory.buildSuccessFactory(workersList);

	}

	// 重置密码
	@RequestMapping(value = "/resetPass", method = RequestMethod.POST)
	public Result resetPass(@RequestBody User user) {
		String username = user.getUsername();
		String password = "123456";

		username = HtmlUtils.htmlEscape(username);
		user.setUsername(username);
		int times = 2;
		// 得到 hash 后的密码
		String encodedPassword = new SimpleHash("md5", password, user.getSalt(), times).toString();
		user.setPassword(encodedPassword);
		int i = userService.resetPass(user);
		return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("修改失败");

	}

	// 修改密码
	@RequestMapping(value = "/updatePass", method = RequestMethod.POST)
	public Result updatePass(@RequestParam Map<String, Object> params) {
		
		Subject subject = SecurityUtils.getSubject();
		String username =  (String) params.get("username");
		String oldpassword = (String) params.get("oldpassword");
		String newPassword = (String) params.get("newpassword");
		User user = userService.findByUsername(username);
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, oldpassword);
		try {
			subject.login(usernamePasswordToken);					
			User user2 = new User();
			user2.setUsername(username);
			user2.setSalt(user.getSalt());	
			int times = 2;
			String encodedPassword = new SimpleHash("md5", newPassword, user2.getSalt(), times).toString();
			user2.setPassword(encodedPassword);
			int i = userService.updatePass(user2);
			return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("修改失败");
		} catch (AuthenticationException e) {
			
			String message = "原密码错误";
			return ResultFactory.buildFailFactory(message);
		}
		
		
			
	
		
		
	
		
		
		
	}

	@RequestMapping(value = "/updateWorkers", method = RequestMethod.POST)

	public Result updateWorkers(@RequestBody User user) {
		int i = userService.updateWorkers(user);
		return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("修改失败");

	}

	@RequestMapping(value = "/updateCustomer", method = RequestMethod.POST)
	public Result updateCustomer(@RequestBody User user) {
		int i = userService.updateCustomer(user);
		return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("修改失败");
	}

	@PostMapping("/deleteUser")
	public Result deleteUser(Integer id) {
		int i = userService.deleteUser(id);
		int j = userService.deleteByUid(id);
		return j > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("删除成功");
	}

	@GetMapping("/UserPower")
	public Result UserPower(@RequestParam Map<String, Object> params) {

		Set<String> pSet = new HashSet<>();
		User userpower = userService.userPower(params);
		if (userpower.getPowername() != null) {
			pSet.addAll(Arrays.asList(userpower.getPowername().trim().split(",")));
			for (String ss : pSet) {
				if (ss.equals(params.get("powername"))) {
					return ResultFactory.buildSuccessFactory(true);
				}
			}
		}
		return ResultFactory.buildFailFactory("无该权限");
	}
	
	@PostMapping("/updateUserstate")
	public Result updateUserstate(Integer userstate,String username) {
		
			int i  = userService.updateUserstate(userstate, username);
			return i > 0 ? ResultFactory.buildSuccessFactory(true) : ResultFactory.buildFailFactory("修改成功");	
	}
	
	 @GetMapping("/findAllUser")	  
	  public Result findAllmenus(@RequestParam Map<String, Object> params) {
		 	int pagesize2 = (Integer.valueOf((String)params.get("currentPage"))-1)*Integer.valueOf((String)params.get("pagesize"));
		 	params.put("pagesize2",pagesize2);
		 	Integer id = null;
		 	List<Role> userList = userService.Workers(id);
		 	int count = userList.size();
		 	List<User> users = userService.Users(params);
		 	HashMap<String, Object> hs = new HashMap<>();
			hs.put("users", users);
			hs.put("count",count);
		  			 
		 return ResultFactory.buildSuccessFactory(hs);
		  
	  }
	

}
